package com.gmail.hasszhao.testvolley;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.gmail.hasszhao.testvolley.task.TaskHelper;

public final class MainActivity extends BasicActivity implements Response.Listener<String>, Response.ErrorListener, ImageLoader.ImageListener {

    public static final int LAYOUT = R.layout.activity_main;
    public static final String TINY_URL = "http://tinyurl.com/api-create.php?url=";
    private static final String TAG = "tinyurl task";
    private static final String LOGO = "http://developer.android.com/assets/images/dac_logo.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(LAYOUT);
        TaskHelper.init(getApplicationContext());

        ((NetworkImageView) findViewById(R.id.iv_thumb)).setImageUrl(LOGO, TaskHelper.getImageLoader());
    }

    public void loadCategoryList(View _view) {
        Intent intent = new Intent(CategoryListActivity.ACTION_OPEN_CATEGORYLIST);
        startActivity(intent);
    }

    private String getStringWannaTiny() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(TINY_URL).append(((EditText) findViewById(R.id.et_origin_url)).getText().toString());
        return stringBuilder.toString();
    }

    public void loadTinyURL(View _view) {
        showProgressIndicator();
        RequestQueue queue = TaskHelper.getRequestQueue();
        StringRequest myReq = new StringRequest(Request.Method.GET, getStringWannaTiny(), this, this);
        myReq.setTag(TAG);
        queue.add(myReq);
    }

    @Override
    protected void onPause() {
        TaskHelper.getRequestQueue().cancelAll(MainActivity.TAG);
        dismissProgressIndicator();
        super.onPause();
    }

    @Override
    public void onResponse(String _response) {
        ((EditText) findViewById(R.id.et_origin_url)).setText(_response);
        dismissProgressIndicator();
    }

    @Override
    public void onErrorResponse(VolleyError _error) {
        ((EditText) findViewById(R.id.et_origin_url)).setText(_error.getMessage());
        dismissProgressIndicator();
    }

    public void clear(View _view) {
        ((EditText) findViewById(R.id.et_origin_url)).setText("");
    }

    public void loadImage(View _view) {
        TaskHelper.getImageLoader().get(LOGO, this);
    }

    @Override
    public void onResponse(ImageLoader.ImageContainer _response, boolean _isImmediate) {
        ((ImageView) findViewById(R.id.iv_loaded_image)).setImageBitmap(_response.getBitmap());
    }
}
